package cn.spream.jstudy.designpattern.prototype;

import java.io.*;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 15-1-7
 * Time: 下午2:49
 * To change this template use File | Settings | File Templates.
 */
public class Prototype implements Cloneable, Serializable {

    private Date created = new Date();
    private User user;

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

    public Prototype deepClone() throws IOException, ClassNotFoundException {
        //写入当前对象的二进制流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(this);
        //读出二进制流产生的新对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return (Prototype) objectInputStream.readObject();
    }

    @Override
    public String toString() {
        return "Prototype{" +
                "created=" + created +
                ", user=" + user +
                '}';
    }
}
